package com.turtle.learning.common.exception;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author turtle
 * @since: 2020-05-01
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public String validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        return e.getAllErrors().get(0).getDefaultMessage();
    }

    /**
     * 请求参数验证异常处理
     *
     * @param e 异常
     * @return Object
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return e.getBindingResult().getFieldError().getDefaultMessage();
    }

    /**
     * 请求参数类型验证异常处理
     *
     * @param e 异常
     * @return Object
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Object validExceptionHandler(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        return "参数非法，请检查参数类型";
    }

    /**
     * IllegalArgumentException异常处理
     *
     * @param e 异常
     * @return Object
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Object validExceptionHandler(IllegalArgumentException e) {
        log.error((e.getMessage()), e);
        return e.getMessage();
    }

}
